package com.yihaodian.search.broker.shard;

import java.util.HashMap;
import java.util.Map;

import com.yihaodian.api.client.HedwigServiceProvider;
import com.yihaodian.api.index.IndexRequest;

/**
 * request to given node.
 * 
 */
public class ShardIndexClient {
	static long timeout = 5000;
	static long readTimeout = 3000;

	Map<String, ShardIndexService> shardIndexServices = new HashMap<String, ShardIndexService>();

	public ShardIndexClient() {

	}

	/**
	 * 
	 * @param shard
	 * @return
	 */
	ShardIndexService shardSearchService(String ip, int port) {
		String key = key(ip, port);
		ShardIndexService service = shardIndexServices.get(key);

		if (service == null) {
			synchronized (this) {
				service = shardIndexServices.get(key);

				if (service == null) {
					service = HedwigServiceProvider.getProxy(
							HedwigServiceProvider.serviceName_shardIndex,
							HedwigServiceProvider.serviceVersion(),
							ShardIndexService.class, timeout, readTimeout, ip,
							port);
					shardIndexServices.put(key, service);
				}
			}
		}

		return service;
	}

	public void index(String ip, int port, ShardIndexRequest request) {
		ShardIndexService indexService = shardSearchService(ip, port);
		indexService.index(request);
	}

	String key(String ip, int port) {
		return ip + port;
	}
}
